﻿using Microsoft.AspNetCore.Mvc;
using Urs.Data.Domain.Directory;
using Urs.Plugin.Weixin.MiniSDK.Models;
using Urs.Services.Configuration;
using Urs.Services.Localization;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Framework.Mvc.Filters;

namespace Urs.Plugin.Weixin.MiniSDK.Controllers
{
    [Area("Admin")]
    [AdminAuthorize]
    public class WeixinMiniSDKController : BasePluginController
    {
        private readonly WeixinMiniSDKSettings _openSDKSettings;
        private readonly ISettingService _settingService;
        private readonly ILocalizationService _localizationService;
        private readonly IPermissionService _permissionService;

        public WeixinMiniSDKController(IPermissionService permissionService,
            WeixinMiniSDKSettings openSDKSettings,
            ISettingService settingService,
            ILocalizationService localizationService)
        {
            this._openSDKSettings = openSDKSettings;
            this._settingService = settingService;
            this._localizationService = localizationService;
            this._permissionService = permissionService;
        }

        #region Methods

        public IActionResult Configure()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageWidgets))
                return RedirectToAction("Unauthorized", "Security");

            var model = new ConfigurationModel
            {
                AppId = _openSDKSettings.AppId,
                AppSecret = _openSDKSettings.AppSecret,
            };
            return View("~/Plugins/Weixin.MiniSDK/Views/Configure.cshtml", model);
        }

        [HttpPost, ActionName("Configure")]
        public IActionResult Configure(ConfigurationModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageWidgets))
                return RedirectToAction("Unauthorized", "Security");
            _openSDKSettings.AppId = model.AppId;
            _openSDKSettings.AppSecret = model.AppSecret;
            _settingService.SaveSetting(_openSDKSettings);
            //now clear settings cache
            _settingService.ClearCache();

            return Json(new { success = 1 });
        }

        #endregion
    }
}